<?php

/**
 *
 * lazy~
 */
function P($x) {
    print_r($x);
    exit;
}

/*
 * file upload rename rule
 */

function uploadName() {
    return time() . getCode();
}

function storeiconThumb($img) {
    if (empty($img)) {
        return 'http://sharesdk.cn/Public/Frontend/images/sharesdk_logo.png';
    }



    $root = dirname(dirname(dirname(__FILE__))) . DS . 'media' . DS . 'app' . DS;

    $width = 120;
    $fileName = substr($img, strrpos($img, '/') + 1, strlen($img));
    $thumbName = substr($fileName, 0, strrpos($fileName, '.')) . '_' . $width . substr($fileName, strrpos($fileName, '.'), strlen($fileName));
    $thumb = __ROOT__ . '/media/app/' . $thumbName;

    if (file_exists($root . $thumbName)) {

        return $thumb;
    } else {
        return $img;
    }
}

function pwdHash($password, $type = 'md5') {
    return hash($type, $password);
}

function showEmpty($value) {
    if ($value === '' || $value === null) {
        return '<small>无数据</small>';
    }
    return $value;
}
function showZero($value) {
    if ($value === '' || $value === null) {
        return '0';
    }
    return $value;
}
function CS($group = '', $expire = '', $key = '') {
    $array['cache']['set'] = true;
    if ($group) {
        $array['cache']['group'] = $group;
        if (empty($expire)) {
            $expire = 180;
        }
    }
    if ($key) {
        $array['cache']['key'] = $key;
    }
    if ($expire) {
        $array['cache']['expire'] = $expire;
    }
    return $array;
}

/**
 * 返回一字符串，十进制 number 以 radix 进制的表示。
 * @param dec       需要转换的数字
 * @param toRadix    输出进制。当不在转换范围内时，此参数会被设定为 2，以便及时发现。
 * @return    指定输出进制的数字
 */
function dec2Any($shu, $jinzhi) {
    $zifu = "";
    while ($shu != 0) {
        $linshi = $shu % $jinzhi;
        switch ($jinzhi) {
            case 2:
                $zifu = decbin($shu);
                return $zifu;
            case 8:
                $zifu = decoct($shu);
                return $zifu;
            case 16:
                $zifu = dechex($shu);
                return $zifu;
            case 36:
                if ($linshi >= 10) {

                    $zifu.= chr(($linshi + 55));
                } else {
                    $zifu.= $linshi;
                }
                break;
            case 62:
                if (($linshi >= 10) && ($linshi < 36)) {
                    $zifu.= chr($linshi + 55);
                    break;
                }
                if (($linshi >= 36) && ($linshi < 62)) {
                    $zifu.= chr($linshi + 61);
                    break;
                }
                $zifu.= $linshi;
                break;
            default:
                $zifu.= $linshi;
                break;
        }
        $shu = intval($shu / $jinzhi);
    }
    return strrev($zifu);
}

/**
 *
 * bug record for developing
 */
function debug($message) {
    Log::write($message, $level = 'DEBUG:', $type = '', $destination = 'debug.log', $extra = '');
}

/**
 *
 * 返回一串随机数
 * @param integer $length length of return vold
 * @param integer $mode character string 
 */
function getCode($length = 4, $mode = 0) {
    switch ($mode) {
        case '1':
            $str = '1234567890';
            break;
        case '2':
            $str = 'abcdefghijklmnopqrstuvwxyz';
            break;
        case '3':
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
        default:
            $str = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
    }

    $result = '';
    $l = strlen($str) - 1;
    $num = 0;

    for ($i = 0; $i < $length; $i++) {
        $num = rand(0, $l);
        $a = $str[$num];
        $result = $result . $a;
    }
    return $result;
}

/**
 *
 * 利用json编码
 */
function getJson($rows, $total) {

    if (empty($rows)) {
        $rows = array();
    }
    $json['total'] = $total;
    $json['rows'] = $rows;
    return json_encode($json);
}

/**
 * 邮件发送类 PHPMailer 整合
 * @param string $to 接受邮件方
 * @param string $subject 邮件标题
 * @param string $body 邮件正文
 * @param string $altBody 邮件说明
 * @return bool 
 */
function phpMail($to, $subject = 'Appgo', $body = '', $altBody = "Appgo") {
    vendor('PHPMailer.class#phpmailer');
    $mail = new PHPMailer(true); //New instance, with exceptions enabled
    $mail->IsSMTP();                           // tell the class to use SMTP
    $mail->SMTPAuth = true;                  // enable SMTP authentication
    $mail->Port = C('SMTP_PORT');                    // 25
    $mail->Host = C('SMTP_HOST'); // localhost
    $mail->Username = C('SMTP_USERNAME');     // support
    $mail->Password = C('SMTP_PASSWORD');            // lin12345
    $mail->CharSet = "UTF-8";
    //$mail->IsSendmail();  // tell the class to use Sendmail
    $mail->SMTPDebug = 0;
    $mail->AddReplyTo(C('SMTP_REPLY'), C('SMTP_REPLY_NAME'));
    $mail->From = C('SMTP_SEND'); //service@sharesdk.cn
    $mail->FromName = C('SMTP_SEND_NAME');
    $mail->AddAddress($to, '会员您好');
    $mail->Subject = $subject;
    $mail->AltBody = $altBody; // optional, comment out and test
    $mail->WordWrap = 80; // set word wrap

    $mail->MsgHTML($body);
    $mail->IsHTML(true); // send as HTML

    if ($mail->Send()) {
        return true;
    } else {
        return false;
    }
}

/**
  +----------------------------------------------------------
 * 字符串截取，支持中文和其他编码 
  +----------------------------------------------------------
 * @static 
 * @access public 
  +----------------------------------------------------------
 * @param string $str 需要转换的字符串 
 * @param string $start 开始位置 
 * @param string $length 截取长度 
 * @param string $charset 编码格式 
 * @param string $suffix 截断显示字符 
  +----------------------------------------------------------
 * @return string 
  +----------------------------------------------------------
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) {
    if (mb_strlen($str, $charset) <= $length)
        return $str;
    if (function_exists("mb_substr")) {
        if ($suffix)
            return mb_substr($str, $start, $length, $charset) . "...";
        else
            return mb_substr($str, $start, $length, $charset);
    }
    elseif (function_exists('iconv_substr')) {
        if ($suffix)
            return iconv_substr($str, $start, $length, $charset) . "...";
        else
            return iconv_substr($str, $start, $length, $charset);
    }
    $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("", array_slice($match[0], $start, $length));
    if ($suffix)
        return $slice . "…";
    return $slice;
}

function xml_decode($xml, $root = 'response') {
    $search = '/<(' . $root . ')>(.*)<\/\s*?\\1\s*?>/s';
    $array = array();
    if (preg_match($search, $xml, $matches)) {
        $array = xml_to_array($matches[2]);
    }
    return $array;
}

function xml_to_array($xml) {
    $search = '/<(\w+)\s*?(?:[^\/>]*)\s*(?:\/>|>(.*?)<\/\s*?\\1\s*?>)/s';
    $array = array();
    if (preg_match_all($search, $xml, $matches)) {
        foreach ($matches[1] as $i => $key) {
            $value = $matches[2][$i];
            if (preg_match_all($search, $value, $_matches)) {
                $array[$key] = xml_to_array($value);
            } else {
                if ('ITEM' == strtoupper($key)) {
                    $array[] = html_entity_decode($value);
                } else {
                    $array[$key] = html_entity_decode($value);
                }
            }
        }
    }
    return $array;
}

function formatChangelog($log) {
    return str_replace("\n", '<br/>', $log);
}

/**
 * 获取客户端浏览器类型
 * @param  string $glue 浏览器类型和版本号之间的连接符
 * @return string|array 传递连接符则连接浏览器类型和版本号返回字符串否则直接返回数组 false为未知浏览器类型
 */
function get_client_browser($glue = null) {
    $browser = array();
    $agent = $_SERVER['HTTP_USER_AGENT']; //获取客户端信息

    /* 定义浏览器特性正则表达式 */
    $regex = array(
        'ie' => '/(MSIE) (\d+\.\d)/',
        'chrome' => '/(Chrome)\/(\d+\.\d+)/',
        'firefox' => '/(Firefox)\/(\d+\.\d+)/',
        'opera' => '/(Opera)\/(\d+\.\d+)/',
        'safari' => '/Version\/(\d+\.\d+\.\d) (Safari)/',
    );
    foreach ($regex as $type => $reg) {
        preg_match($reg, $agent, $data);
        if (!empty($data) && is_array($data)) {
            $browser = $type === 'safari' ? array($data[2], $data[1]) : array($data[1], $data[2]);
            break;
        }
    }
    $other = array(0 => 'Other', '1');

    return empty($browser) ? $other : (is_null($glue) ? $browser : implode($glue, $browser));
}

/**
 * 验证手机
 * @param string $value
 * @param string $match
 * @return boolean
 */
function checkMobile($value, $match = '/^13[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$|14[0-9]{1}[0-9]{8}$|189[0-9]{8}$/') {
    $v = trim($value);
    if (empty($v))
        return false;
    return preg_match($match, $v);
}

/**
 * 验证密码
 * @param string $value
 * @param int $length
 * @return boolean
 */
function isPWD($value, $minLen = 6, $maxLen = 18) {
    $match = '/^[\\~!@#$%^&*()-_=+|{}\[\],.?\/:;\'\"\d\w]{' . $minLen . ',' . $maxLen . '}$/';
    $v = trim($value);
    if (empty($v))
        return false;
    return preg_match($match, $v);
}

/**
 * 验证QQ
 * @param string $value
 * @param int $length
 * @return boolean
 */
function is_QQ($value, $match = "^[1-9][0-9]{4,}$") {
    return true;

}

/**
 * 验证身份证号码
 * @param string $value
 * @param string $match
 * @return boolean
 */
function isIDcard($value, $match = '/^\d{6}((1[89])|(2\d))\d{2}((0\d)|(1[0-2]))((3[01])|([0-2]\d))\d{3}(\d|X)$/i') {
    $v = trim($value);
    if (empty($v))
        return false;
    else if (strlen($v) > 18)
        return false;
    return preg_match($match, $v);
}

/**
 * *
 * 验证URL
 * @param string $value
 * @param string $match
 * @return boolean
 */
function isURL($value, $match = '/^(http:\/\/)?(https:\/\/)?([\w\d-]+\.)+[\w-]+(\/[\d\w-.\/?%&=]*)?$/') {
    $v = strtolower(trim($value));
    if (empty($v))
        return false;
    return preg_match($match, $v);
}

/**
 * @package     二维数组排序
 *
 *
 * Sort an two-dimension array by some level two items use array_multisort() function.
 *
 * sysSortArray($Array,&quot;Key1&quot;,&quot;SORT_ASC&quot;,&quot;SORT_RETULAR&quot;,&quot;Key2&quot;……)
 * @param  array   $ArrayData   the array to sort.
 * @param  string  $KeyName1    the first item to sort by.
 * @param  string  $SortOrder1  the order to sort by(&quot;SORT_ASC&quot;|&quot;SORT_DESC&quot;)
 * @param  string  $SortType1   the sort type(&quot;SORT_REGULAR&quot;|&quot;SORT_NUMERIC&quot;|&quot;SORT_STRING&quot;)
 * @return array                sorted array.
 */
function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR")
{
    if(!is_array($ArrayData))
    {
        return $ArrayData;
    }

    // Get args number.
    $ArgCount = func_num_args();

    // Get keys to sort by and put them to SortRule array.
    for($I = 1;$I < $ArgCount;$I ++)
    {
        $Arg = func_get_arg($I);
        if(!eregi("SORT",$Arg))
        {
            $KeyNameList[] = $Arg;
            $SortRule[]    = '$'.$Arg;
        }
        else
        {
            $SortRule[]    = $Arg;
        }
    }

    // Get the values according to the keys and put them to array.
    foreach($ArrayData AS $Key => $Info)
    {
        foreach($KeyNameList AS $KeyName)
        {
            ${$KeyName}[$Key] = $Info[$KeyName];
        }
    }

    // Create the eval string and eval it.
    $EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
    eval ($EvalString);
    return $ArrayData;
}
function std_class_object_to_array($stdclassobject) {
    $_array = is_object($stdclassobject) ? get_object_vars($stdclassobject) : $stdclassobject;
    foreach ($_array as $key => $value) {
        $value = (is_array($value) || is_object($value)) ? std_class_object_to_array($value) : $value;
        $array[$key] = $value;
    }
    return $array;
}

    /**
     * 
     * @param string $url 请求地址
     * @param array $postFields 请求参数
     * @return string
     * @throws Exception
     */
    function mycurl($url, $postFields = null) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //https 请求
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        if (is_array($postFields) && 0 < count($postFields)) {
            $postBodyString = "";
            $postMultipart = false;
            foreach ($postFields as $k => $v) {

                if ("@" != substr($v, 0, 1)) {//判断是不是文件上传
                    $k = strtolower($k);
                    $postBodyString .= "$k=" . urlencode($v) . "&";
                } else {//文件上传用multipart/form-data，否则用www-form-urlencoded
                    $postMultipart = true;
                }
            }
            unset($k, $v);
            curl_setopt($ch, CURLOPT_POST, true);
            if ($postMultipart) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
            }
        }
        $reponse = curl_exec($ch);

        if (curl_errno($ch)) {
            return false;
        } else {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode) {
                return false;
            }
        }
        curl_close($ch);
        return $reponse;
    }

    function showidenfity($value) {
        if($value) {
            return $value;
        }
        return 'default';
    }
    function showstatus($value) {
        if($value) {
            return 'On';
        }
        return 'Off';
    }
    function showData($datatime){
        return date('Y-m-d', strtotime($datatime));
    }

    function getProductImage($image, $thumb = true){
        $thumb_name = '';

        if($thumb) {
            $thumb_name = 'thumb_';
        }
        return __ROOT__ . C('UPLOAD_PATH_PRODUCT')  . $thumb_name . $image;
    }
?>
